from pyasn1.type import univ, namedtype
from pyasn1.codec.der import encoder

# 定义ASN.1结构
class SM2Signature(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('r', univ.Integer()),
        namedtype.NamedType('s', univ.Integer())
    )

# 提供的R和S值
# r_hex = '1A006C079B08BE4C56438F7076F945914B9E3595C37F34E5E1911DF1EA612E26'
# s_hex = 'F128CC46F1C7CDE9DB97EC0CD6190B587179F688A548275D030649D34C0D61AB'
# r_hex = '257E754CE5D6568233B5A8F616D7BB42B19E9F4F1204FCE0E486FEE959DDECE4'
# s_hex = '6BCABA3BD56714E20C84407577BA80A098B3FE9C680876F95AF81736CAD005F0'
# r_hex = 'D4D11FCC2709144E9703AF851446B78C98112D6FDEBF68C0E990168603C95C7D'
# s_hex = '0FAEAFAF85A2ECBC68F261BB3AA5337835D95FFCA5CAFAD69AF5E134F76E06E4'
# r_hex = '231CF078B6D3157B1AB42DD7CA404662864E2018D58D8921C6B85DAABF0807A2'
# s_hex = '9FB709039F072736BE19E7D2182CCD21B64730208B235E339CF66EDFEA86986D'
# r_hex = 'ED8E58F3A6C1CFF1BAB3D019C73136E582EBE5EC83B98E5420E78DB2A4FDA358'
# s_hex = 'AB6D20DE06F775FA6EC89322D7808D91FC9E487A575D6F63E4A58276D224811B'
# r_hex = 'A718BBC4934099EBD089C4D674F4DC4CC9636897B23102EC12FC3EDD781DB3D8'
# s_hex = '96B50FB41C00E2BA3EFDCBD5093D3E2E34DB370C2AA5B6B94C7E9A52B491C1A0'
r_hex = '4B7DFD375F53262BCB9083CF554DB4BBA08A026FF4173203BCD3F339F3CBB330'
s_hex = '0EC12D0C4B31D461623FC657A6A8F65E5D4CF2BC0BEA6E35E8CAB31FD0BC7057'

# 将十六进制字符串转换为整数
r_int = int(r_hex, 16)
s_int = int(s_hex, 16)

# 检查S的最高位，如果需要，补零
s_bytes = bytes.fromhex(s_hex)
if s_bytes[0] & 0x80:
    s_int = int('00' + s_hex, 16)

# 创建SM2Signature实例
signature = SM2Signature()
signature.setComponentByName('r', r_int)
signature.setComponentByName('s', s_int)

# DER编码
der_encoded = encoder.encode(signature)
print("DER编码结果（十六进制）:")
print(der_encoded.hex().upper())
